<template>
  <div class="imgList">
    <!-- 目录结构树 -->
    <dir-tree ref="dirTree" @SelectNode="handleSelectTreeNode"></dir-tree>
    <div class="sourceList">
      <div class="tb-head">
        <el-button @click="dialogShow=true" icon="upload2">上传图片</el-button>
        <a v-if="selNum" class="el-button el-button--default"
        :href="`${baseUrl}/content/source/download?sourceIds=${checkList.filter(item => item).join(',')}&__token=${token}`">
          下载
        </a>
        <a v-else class="el-button el-button--default is-disabled">
          下载
        </a>
        <el-button @click="handleMoveDirClick" :disabled="!selNum">移动文件夹</el-button>
        <span class="selNum">已选 <i class="red">{{selNum}}</i> 张</span>
        <el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
      </div>
      <div class="sourceBox"  v-loading="loading">
        <div class="noMessage" v-if="sourceList.list.length==0">暂无图片内容</div>
        <image-item
          ref="imgItem"
          v-for="item,n in sourceList.list"
          :data="item"
          :checked.sync="checkList[n]"
          @checkChange="handleCheckChange"
          @delete="checkList.fill(false)"
          :key="n.toString()"></image-item>
      </div>
      <!-- 上传视频弹出层 -->
      <el-dialog title="新建图片" :visible.sync="dialogShow" width="30%" custom-class="dialog_upload" @open="initUpload">
        <el-row>
          <div class="field-tit">内容性质:</div>
          <div class="field-bd">
            <el-select v-model="contentType">
              <el-option v-for="item,n in attrs" :label="item.name" :value="item.id" :key="n.toString()"></el-option>
            </el-select>
          </div>
        </el-row>
        <el-row>
          <div class="field-tit">选择文件:</div>
          <div class="field-bd">
            <el-upload ref="upload"
              class="upload"
              :action="baseUrl + '/content/source/upload/image'"
              :data="params"
              :headers="headers"
              :on-success="handleSuccess"
              :on-error="handleError"
              :before-upload="handleBeforeUpload"
              :auto-upload="false"
              :file-list="fileList">
              <el-input placeholder="请选择文件" class="input-upload">
                <el-button slot="append">浏览</el-button>
              </el-input>
              <div slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png文件</div>
            </el-upload>
          </div>
        </el-row>
        <div slot="footer">
          <el-button @click="dialogShow=false;">关闭</el-button>
          <el-button type="primary" @click="handleSaveImg" :loading="isSave">保存</el-button>
        </div>
      </el-dialog>
    </div>
    <transition name="router-fade" mode="out-in">
      <div v-if="isMoveDir" class="mask" @click="isMoveDir=false"></div>
    </transition>
  </div>
</template>
<script>
  import {mapState, mapActions} from 'vuex'
  import dirTree from '@/components/common/content/dirTree'
  import env from '@/config/env'
  import imageItem from '@/components/common/content/imageItem'
  export default {
    props: ['loading'],
    components: {dirTree, imageItem},
    data () {
      return {
        baseUrl: env.baseUrl,
        pid: null,
        name: '',
        fileList: [],
        checkList: new Array(12).fill(false),
        checkAll: false,
        contentType: null,
        isMoveDir: false,
        dialogShow: false,
        isSave: false
      }
    },
    computed: {
      ...mapState({
        sourceList: state => state.sourceManage.imgList,
        currentDir: state => state.sourceManage.currentDir,
        attrs: state => state.contentManage.contentType
      }),
      // 文件上传附加的头部
      headers () {
        return {
          UBToken: localStorage.getItem('UBToken')
        }
      },
      // 文件上传附加的参数
      params () {
        return {
          contentType: this.contentType,
          pid: this.currentDir
        }
      },
      selNum () {
        return this.checkList.filter(item => item).length
      },
      token () {
        return localStorage.getItem('UBToken')
      }
    },
    methods: {
      ...mapActions(['moveSourceDir']),
      // 上传成功回调
      handleSuccess (res, file, fileList) {
        this.isSave = false
        this.dialogShow = false
        this.$bus.$emit('reloadSource')
        if (res.code !== 1) {
          this.$message({
            type: 'warning',
            message: res.msgZ
          })
          fileList.forEach((item, n) => {
            if (item === file) {
              fileList.splice(n, 1)
            }
          })
        }
      },
      // 上传失败回调
      handleError (res) {
        this.isSave = false
        this.$message.warning(res.msgZ)
      },
      // 上传前的检验
      handleBeforeUpload (file) {
        const allowTypes = ['image/jpg', 'image/jpeg', 'image/png']
        if (allowTypes.indexOf(file.type) === -1) {
          this.$message.warning('格式不支持')
          return false
        }
        this.isSave = true
      },
      // 保存
      handleSaveImg () {
        if (!this.contentType) {
          this.$message.warning('请选择内容性质')
          return
        }
        if (!this.$refs.upload.uploadFiles.length) {
          this.$message.warning('请选择图片内容')
          return
        }
        this.$refs.upload.submit()
      },
      // 初始化上传
      initUpload () {
        this.contentType = ''
        this.$refs.upload && this.$refs.upload.clearFiles()
      },
      // 全选
      handleCheckAllChange (e) {
        let tempArr = this.$_.cloneDeep(this.checkList)
        if (e) {
          this.checkList = this.sourceList.list.map(item => item.id)
        } else {
          this.checkList = tempArr.fill(false, 0, this.$refs.imgItem.length)
        }
      },
      handleCheckChange () {
        this.checkAll = (this.checkList.filter(item => item).length === this.$refs.imgItem.length)
      },
      async handleSelectTreeNode () {
        if (!this.isMoveDir) {
          this.checkList.fill(false)
          this.checkAll = false
          this.$bus.$emit('reloadSource')
        } else {
          await this.$confirm('是否确定移到改目录?')
          const ids = this.checkList.filter(item => {
            return item
          })
          const res = await this.moveSourceDir({
            aimId: this.$refs.dirTree.currentDir,
            imageIds: ids
          })
          if (res.data.code === 1) {
            this.$message.success('移动成功')
            this.isMoveDir = false
            this.$bus.$emit('reloadSource')
            this.checkList = new Array(10).fill(false)
            this.checkAll = false
          }
        }
      },
      // 移动文件夹
      handleMoveDirClick () {
        this.isMoveDir = true
      }
    }
  }
</script>
<style lang="scss">
  .imgList{
    .tb-head{
      a{text-decoration:none;}
    }
    .selNum{margin:0 15px;font-size:14px;}
    .dirTree .el-tree{position:relative;z-index:111;}
    .mask{position:fixed;top:0;right:0;bottom:0;left:0;background:rgba(0,0,0,.5);z-index:100}
  }
</style>
